<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ titles }}</span>
          <el-button size="mini" style="float: right" @click="router.go(-1)">返回</el-button>
        </div>
      </template>
      <el-form ref="form" :model="formData" label-position="left" label-width="90px" margin-left="10px">
        <el-form-item label="名称：">
          <el-input v-model="formData.homework_name" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="类型：">
          <el-radio-group v-model="formData.type">
            <el-radio label="三维">三维</el-radio>
            <el-radio label="AI">AI</el-radio>
            <el-radio label="其他">其他</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="日期：">
          <el-date-picker v-model="formData.work_date" type="date" placeholder="选择日期"
            style="width: 150px"></el-date-picker>
        </el-form-item>

        <el-form-item label="备注：">
          <el-input v-model="formData.notes" style="width: 400px" type="textarea" :rows="6"></el-input>
        </el-form-item>

        <el-form-item label="文件：">
          <el-upload v-model:file-list="formData.fileList" class="upload-demo" :action="`${baseURL}/api/uploadHomework`"
            :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" multiple :name="'files'"
            list-type="picture">
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                <!-- jpg/png files with a size less than 500kb -->
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="已上传文件：" v-show="hasFileList.length > 0">
          <ul class="hasFileList">
            <li v-for="(file, index) in hasFileList" :key="index">
              <template v-if="tool.isImage(file.url)">
                <el-image :src="`${baseURL}/${file.url}`" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                  :preview-src-list="file.url.split(',').map((url) => `${baseURL}/${url.trim()}`)
                    " :initial-index="0" fit="cover" @load="onImageLoad" />
              </template>
              <template v-else-if="tool.isVideo(file.url)">
                <video controls :src="`${baseURL}/${file.url}`" class="video" preload="metadata"></video>
              </template>
              <template v-else>
                <a :href="`${baseURL}/${file.url}`" class="file-download" target="_blank">
                  <el-button type="primary" round>
                    点击查看{{ file.url.split('/').pop().split('.').pop() }}文件<el-icon class="el-icon--right">
                      <View />
                    </el-icon>
                  </el-button>
                </a>
              </template>
              <el-button type="danger" :icon="Delete" circle @click="delFile(file.id)" />
            </li>
          </ul>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import homeworkApi from '../../api/homework'
import tool from '../../tools/tool'
const router = useRouter()
const route = useRoute()
const isEdit = ref(false)
const formData = ref({
  homework_name: '',
  type: '',
  work_date: new Date(),
  notes: '',
  author: '',
  fileList: [],
})
const titles = ref()
const hasFileList = ref([])   //已经存在的数据

// 获取全局变量
const baseURL = window.globalConfig.baseURL
const username = sessionStorage.getItem('username') //日志需要

const submitForm = async () => {
  //判断是否正确输入
  if (!formData.value.homework_name) {
    ElMessage.warning('请填写作业名称')
    return
  }

  //把work_date转化成时间格式
  const workDate = new Date(formData.value.work_date)
  const year = workDate.getFullYear();
  const month = String(workDate.getMonth() + 1).padStart(2, '0'); // getMonth() 返回的月份是从0开始的，所以要加1
  const day = String(workDate.getDate()).padStart(2, '0');
  const hours = String(workDate.getHours()).padStart(2, '0');
  const minutes = String(workDate.getMinutes()).padStart(2, '0');
  const seconds = String(workDate.getSeconds()).padStart(2, '0');

  formData.value.work_date = `${year}-${month}-${day}`;

  formData.value.author = username

  //判断是否有文件
  // if (formData.value.fileList.length == 0) {
  //     ElMessage.warning('请上传文件')
  //     return
  // }

  if (isEdit.value) {
    const data = {
      id: route.query.id,
      data: formData.value,
      username: username,
    }
    data.data = formData.value

    const res = await homeworkApi.updateHomework(data)
    // 处理后台返回的结果，你可以根据具体情况进行处理
    if (res.data.success) {
      ElMessage.success('更新成功')
      router.go(-1)
      // router.push('/week_report')
    } else {
      ElMessage.error('更新失败')
    }
  } else {
    // 新增，提交到后台
    formData.value.username = username
    const res = await homeworkApi.addHomework(formData.value)
    // 处理后台返回的结果，你可以根据具体情况进行处理
    if (res.data.id) {
      ElMessage.success('新增成功')
      router.go(-1)
      // router.push('/week_report')
    } else {
      ElMessage.error('新增失败')
    }
  }
}
onMounted(async () => {
  console.log(route.query)
  if (route.query.id) {
    //请求数据
    const orderRes = await homeworkApi.getHomework({ id: route.query.id })
    console.log(orderRes.data[0])
    Object.assign(formData.value, orderRes.data[0])
    titles.value = '编辑作业'
    isEdit.value = true
    formData.value.fileList = []
    const fileRes = await homeworkApi.getHomeworkFilesById({ id: route.query.id })
    hasFileList.value = fileRes.data
  } else {
    titles.value = '新增作业'
  }
})

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePreview = (file) => {
  console.log(file)
}

const handleSuccess = () => {
  console.log(formData.value.fileList)
}

const delFile = async (id) => {
  ElMessageBox.confirm('确定要删除该文件吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const username = sessionStorage.getItem('username')
      const res = await homeworkApi.delHomeworkFile({ id: id, username: username })
      if (res.data.success) {
        ElMessage.success('删除成功')
        const fileRes = await homeworkApi.getHomeworkFilesById({ id: route.query.id })
        hasFileList.value = fileRes.data
      } else {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

</script>

<style scoped>
.el-button-group {
  vertical-align: baseline;
}

el-group {
  position: relative;
  display: inline-block;
}

.el-progress--line {
  margin-bottom: 15px;
  width: 248px;
}

.nameDialog li {
  cursor: pointer;
  margin-bottom: 10px;
  text-decoration: underline;
}

@media screen and (max-width: 768px) {
  .el-card {
    overflow: auto;
  }
}

.hasFileList {
  width: 250px;
  /* height: 200px; */
  /* line-height: 200px; */
  overflow: hidden;
  cursor: pointer;
  display: inline-block;
  padding: 0;
}

.hasFileList li {
  list-style: none;
  position: relative;
}

.hasFileList .el-image {
  width: 70%;
  display: inline-block;
}

.hasFileList li video {
  width: 70%;
  object-fit: contain;
  height: 100%;
  margin: 10px
}
</style>
